import { useEffect, useState, useCallback } from 'react';
import { message, Popover, Select } from 'antd';
import { Button, Pagination, Row, Col, Modal, Input, Spin, Empty } from 'antd';
import dayjs from 'dayjs';
import debounce from 'lodash.debounce';
import api from '@/api/account';
import CustomizeHeader from '@/components/customizeHeader/customizeHeader';
import { useNavigate } from 'react-router-dom';
import UserEvent from '@/components/userEvent';
import AddModal from './components/addModal';
import { articleList, addArticle, updateArticleId, articleDetail, delArticleId } from '@/api/article';
import moment from 'moment';
import './index.scss';
interface listParams {
    pageNum: number;
    keyword: string;
    status: string;
    minAge: number;
    maxAge: number;
    userGender: any;
    professionId: string;
    personality: string;
    disabled: any;
    currentProvinceCode: string;
    currentCityCode: string;
    currentDistrictCode: string;
    creatioTime: any;
    sTime: string;
    eTime: string;
}
interface DataType {
    articleTitle: string;
    eqSkillTypeName: string;
    createTime: number;
}
const User = props => {
    const link = useNavigate();
    const [loading, setLoading] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
    const [totalRecord, setTotalRecord] = useState(0);
    const [totalActive, setTotalActive] = useState(0);
    const [titleText, setTitleText] = useState<string>('Delete account');
    const [contentTextOne, setContentTextOne] = useState<string>('After confirmation, the user will be deleted.');
    const [contentTextTwo, setContentTextTwo] = useState<string>('This action cannot be undone.');
    const [confirmText, setConfirmText] = useState<string>('Confirm');
    const [openType, setOpenType] = useState<number>(0);
    const [listParams, setListParams] = useState<listParams>({
        pageNum: 1,
        keyword: '',
        status: '',
        minAge: 0,
        maxAge: 200,
        userGender: null,
        professionId: '',
        personality: '',
        disabled: null,
        currentProvinceCode: '',
        currentCityCode: '',
        currentDistrictCode: '',
        creatioTime: [],
        sTime: '',
        eTime: '',
    });
    // const [listParams, setListParams] = useState<listParams>({});
    // const [tableData, setTableData] = useState<DataType[]>([]);
    const [tableData, setTableData] = useState<any[]>([]);
    const [currentInfo, setCurrentInfo] = useState<any>({});
    const [typeFlag, setTypeFlag] = useState<string>('add');
    const inputChange = e => {
        debouncedSave({ ...listParams, keyword: e.target.value, pageNum: 1 });
    };
    const debouncedSave = useCallback(
        debounce(nextValue => setListParams(nextValue), 1500),
        []
    );
    function getAccountList() {
        const { keyword } = listParams;
        console.log(listParams, '接口');
        const params = {
            ...listParams, // 先注释，方便看接口返回的数据
            keyword,
            // pageNum: 1,
            pageSize: 10,
            // startTime: sTime,
            // endTime: eTime,
        };
        setLoading(true);
        articleList(params).then((res: any) => {
            setLoading(false);
            if (res && res.records.length > 0) {
                res.records.map(item => {
                    if (item.userGender == 1) {
                        item.userGenderText = 'Male';
                    } else if (item.userGender == 2) {
                        item.userGenderText = 'Female';
                    } else {
                        item.userGenderText = '-';
                    }
                    item.lastActiveTime =
                        item.lastActiveTime && item.lastActiveTime !== '0'
                            ? moment(item.lastActiveTime).format('DD/MM/YYYY HH:mm:ss')
                            : '-';
                    item.createTime =
                        item.createTime && item.createTime !== '0'
                            ? moment(item.createTime).format('DD/MM/YYYY HH:mm:ss')
                            : '-';
                });
                setTableData(res.records);
                setTotalRecord(res.total);
            } else {
                setTableData([]);
                setTotalRecord(0);
            }
        });
    }
    const handlePageChange = prop => {
        setListParams(state => ({ ...state, pageNum: prop }));
    };
    useEffect(() => {
        getAccountList();
    }, [listParams]);
    const [detailModalOpen, setDetailModalOpen] = useState(false);
    const [detailData, setDetailData] = useState<{
        checklistTaskCount: number;
        notificationTaskCount: number;
        timeBasedTaskCount: number;
        childList: {
            childName: string;
            age: number;
            headShot: string;
            completedTaskCountForToday: number;
            completedTaskTotalCountForToday: number;
            earnedRewardCount: string;
            earnedStarForToday: number;
            earnedTotalStarForToday: number;
            totalStar: number;
        }[];
    }>({ checklistTaskCount: 0, notificationTaskCount: 0, timeBasedTaskCount: 0, childList: [] });
    const showDetailModal = (articleId: string) => {
        api.accountDetail(articleId, res => {
            if (res.code === 200) {
                setDetailData(res.data);
                setDetailModalOpen(true);
            } else {
                message.error(res.message);
            }
        });
    };
    const handleCancel = () => {
        setDetailModalOpen(false);
    };
    const handleChange = (value: string) => {
        setListParams(state => ({ ...state, status: value === 'all' ? '' : value, pageNum: 1 }));
    };
    const [accountModal, setAccountModal] = useState({
        articleId: '',
        open: false,
        isDelete: false,
        disabled: false,
        userId: '',
    });

    const confirmCallBack = value => {
        if (value === 1) {
            const params = {
                articleId: accountModal.articleId,
            };
            setConfirmLoading(true);
            delArticleId(params).then(res => {
                setConfirmLoading(false);
                setAccountModal({ userId: '', articleId: '', open: false, isDelete: false, disabled: false });
                getAccountList();
            });
            //
        } else {
            getAccountList();
        }
    };
    function getValueFromSon(values) {
        // values是子组件filterModal传过来的值
        setFilterVisible(false);
        // 调用查询
        getAccountList();
        setCurrentInfo({});
    }
    const toDetail = (articleId: string) => {
        sessionStorage.setItem('articleId', articleId);
        link('/user/detail');
    };
    const openModal = (obj: any, type: number) => {
        const conTextOne = 'After confirmation, the article will be deleted.';
        const conTextTwo = 'This action cannot be undone.';
        const conConfirmText = 'Delete';
        setTitleText('Delete articles');
        setContentTextOne(conTextOne);
        setContentTextTwo(conTextTwo);
        setConfirmText(conConfirmText);
        setOpenType(type);
        setAccountModal({
            open: true,
            articleId: obj.eqArticleId,
            isDelete: false,
            disabled: obj.disabled,
            userId: '',
        });
    };
    const toInfo = value => {
        const params = {
            articleId: value.eqArticleId,
        };
        articleDetail(params).then(res => {
            const obj = JSON.parse(JSON.stringify(res));
            obj.eqSkillTypeName = value.eqSkillTypeName;
            setTypeFlag('detail');
            setCurrentInfo(obj);
            setFilterVisible(true);
        });
    };
    const addBtn = () => {
        setTypeFlag('add');
        setCurrentInfo({});
        setFilterVisible(true);
    };
    const [filterVisible, setFilterVisible] = useState(false);
    return (
        <>
            <div className="page-main account">
                <div className="container">
                    <div className="search-bar">
                        <div className="page-title">Recommended articles</div>
                        <div className="search-bar-right">
                            <Input
                                className="search-input"
                                placeholder="Search"
                                onChange={inputChange}
                                prefix={
                                    <img
                                        src={require('@/assets/images/search-icon.png')}
                                        style={{ width: 20, height: 20 }}
                                    />
                                }
                            />
                            <div className="addBtnBox flex-center" onClick={() => addBtn()}>
                                + Add article
                            </div>
                        </div>
                    </div>
                    <div className="table">
                        <div className="table-th">
                            <Row>
                                <Col span={8}>Title</Col>
                                <Col span={7}>Relationship skills</Col>
                                <Col span={5}>Creation time</Col>
                                <Col span={4}></Col>
                            </Row>
                        </div>
                        {loading ? (
                            <div className="data_loading flex-center">
                                <Spin tip="Loading" />
                            </div>
                        ) : tableData.length ? (
                            tableData.map((item, index) => (
                                <Row className="table-tr" key={item.eqArticleId}>
                                    <Col span={8}>{item.articleTitle}</Col>
                                    <Col span={7}>{item.eqSkillTypeName}</Col>
                                    <Col span={4}>{item.createTime || '-'}</Col>
                                    <Col span={1}>
                                        <div className="viewBox" onClick={() => toInfo(item)}>
                                            View
                                        </div>
                                    </Col>
                                    <Col span={1}>
                                        <div className="viewBox">
                                            <img
                                                onClick={() => openModal(item, 3)}
                                                src={require('@/assets/images/delIcon.png')}
                                                style={{ width: 20, height: 20 }}
                                            />
                                        </div>
                                    </Col>
                                </Row>
                            ))
                        ) : (
                            <div className="emptyBox">
                                <Empty description="No users available." />
                            </div>
                        )}
                    </div>
                    {totalRecord > 10 ? (
                        <div className="pagination flex-end">
                            <div
                                className={listParams.pageNum === 1 ? 'to-first is-disable' : 'to-first'}
                                onClick={() => {
                                    setListParams(state => ({ ...state, pageNum: 1 }));
                                }}
                            >
                                First
                            </div>
                            <Pagination
                                current={listParams.pageNum}
                                hideOnSinglePage
                                showSizeChanger={false}
                                total={totalRecord}
                                onChange={handlePageChange}
                            />
                            <div
                                className={
                                    totalRecord
                                        ? listParams.pageNum === Math.ceil(totalRecord / 10)
                                            ? 'to-last is-disable'
                                            : 'to-last'
                                        : 'to-last is-disable'
                                }
                                onClick={() => {
                                    setListParams(state => ({
                                        ...state,
                                        pageNum: Math.ceil(totalRecord / 10),
                                    }));
                                }}
                            >
                                Last
                            </div>
                        </div>
                    ) : (
                        ''
                    )}
                </div>
            </div>
            <UserEvent
                params={accountModal}
                onCancel={() =>
                    setAccountModal({ userId: '', articleId: '', open: false, isDelete: false, disabled: false })
                }
                confirmCallBack={confirmCallBack.bind(this)}
                openType={openType}
                titleText={titleText}
                contentTextOne={contentTextOne}
                contentTextTwo={contentTextTwo}
                confirmText={confirmText}
                btnLoading={confirmLoading}
            />
            <AddModal
                open={filterVisible}
                onConfirm={getValueFromSon.bind(this)}
                currentInfo={currentInfo}
                typeFlag={typeFlag}
                onCancel={(isSearch: boolean) => {
                    setFilterVisible(false);
                    console.log(isSearch);
                }}
            />
        </>
    );
};

export default User;
